const app = Vue.createApp({
    data(){
        return{
          cartItems:[
                {id:'1',imageSrc:'images/1.webp',goodsName:'小米6A L型Type-C快充数据线 白色 150cm',price:39, quantity: 1, selected: false},
                {id:'2',imageSrc:'images/2.webp',goodsName:'小米6A Type-C快充数据线 原装同款 白色',price:29, quantity: 1, selected: false},
                {id:'3',imageSrc:'images/3.webp',goodsName:'小米移动电源3 20000mAh USB-C双向快充版 白色',price:129, quantity: 1, selected: false},
                {id:'4',imageSrc:'images/4.webp',goodsName:'米家循环扇 白色',price:349, quantity: 1, selected: false}
            ],  
            allSelected: false,
        }
    },
    computed: {  
      totalPrice() {  
        return this.cartItems.reduce((total, item) => {  
          if (item.selected) {  
            return total + item.price * item.quantity;  
          }  
          return total;  
        }, 0);  
      },
      selectedItemCount() {  
        return this.cartItems.filter(item => item.selected).length;  
      },  
    },
    methods: {  
      incrementQuantity(index) {  
        this.cartItems[index].quantity++;  
        this.updateTotalPrice();  
      },  
      decrementQuantity(index) {  
        if (this.cartItems[index].quantity > 1) {  
          this.cartItems[index].quantity--;  
          this.updateTotalPrice();  
        }  
      },  
      updateTotalPrice() {  
        this.$forceUpdate(); // 强制Vue重新计算并渲染组件  
      }, 
      toggleAllSelected() {  
        this.cartItems.forEach(item => {  
          item.selected = this.allSelected;  
        });  
        this.updateTotalPrice();  
      },  
      checkout() {  
        if (this.cartItems.some(item => item.selected)) {  
          alert('正在结账...');  
          // 在这里实现结账逻辑，比如调用API发送请求等  
        } else {  
          alert('请选择至少一个商品进行结账！');  
        }  
      },  
    },  
    watch: {  
      // 监听cartItems数组变化，当任何一个商品的selected属性变化时，更新全选状态  
      cartItems: {  
        handler() {  
          this.allSelected = this.cartItems.every(item => item.selected);  
        },  
        deep: true, // 深度监听数组变化  
      },  
    },
});
const vm = app.mount("#container");
  